package com.lifesea.notify.mq.handler;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.lifesea.base.entity.PushAppEnums;
import com.lifesea.base.entity.PushConst;
import com.lifesea.base.entity.PushRequest;
import com.lifesea.commons.template.TemplateConst;
import com.lifesea.commons.utils.FreemarkerUtils;
import com.lifesea.commons.utils.PushUtils;
import com.lifesea.general.facade.TemplateFacade;
import com.lifesea.guahao.facade.GhOrderFacade;
import com.lifesea.model.TemplateInfo;
import com.lifesea.model.dto.BookOrderNotifyRequest;
import com.lifesea.model.dto.GhOrderDto;
import com.lifesea.notify.biz.PushBiz;
import com.lifesea.rocketmq.utils.handler.MessageHandler;
import com.lifesea.rocketmq.utils.message.MessageDecoder;
import com.lifesea.rocketmq.utils.message.codec.JsonMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 挂号消息处理器
 */
@Component
public class BookOrderNotifyHandler implements MessageHandler<BookOrderNotifyRequest> {

    @Resource
    private PushBiz pushBiz;
    @Autowired
    private GhOrderFacade orderFacade;
    @Autowired
    private TemplateFacade templateFacade;

    private static final Logger logger = LoggerFactory.getLogger(BookOrderNotifyHandler.class);

    @Override
    public ConsumeConcurrentlyStatus process(BookOrderNotifyRequest data, MessageExt message, ConsumeConcurrentlyContext context) {
        logger.info("[挂号通知]接收,msgId={},notify={}", message.getMsgId(), data);

        try {
            TemplateInfo templateInfo = templateFacade.getTemplateByName(TemplateConst.TP_APP_GH_SUCCESS);
            GhOrderDto orderDto = orderFacade.getDto(data.getOrder().getBookId());
            String content = FreemarkerUtils.format(templateInfo.getTemplateText(), orderDto);

            PushRequest pushRequest = new PushRequest();
            pushRequest.setAppcode(PushAppEnums.resident);
            pushRequest.setEcn(orderDto.getEcn());
            pushRequest.setCategory(PushConst.PUSH_GUAHAO_DOCTOR_CLOSE);
            pushRequest.setBody(content);
            pushRequest.setRefId(String.valueOf(orderDto.getBookId()));

            if (orderDto.getEcn() != null) {
                PushUtils.send(pushRequest);
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            logger.error("[挂号通知]处理失败", e);
        }
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }


    @Override
    public MessageDecoder<BookOrderNotifyRequest> getMessageDecoder() {
        return new JsonMessageDecoder<>(BookOrderNotifyRequest.class);
    }
}
